package com.naizhuai.Model.db.user;

import com.naizhuai.MainActivity;
import com.naizhuai.Model.AccountHelper;

/**
 * @author：lichenxi
 * @date 2018/2/27 19
 * email：525603977@qq.com
 * Fighting
 */
public class UserRepository implements UserDataSourse {
    private static UserRepository INSTANCE = null;

    private UserDataSourse localUserData;
    private UserDataSourse remoteUserData;

    public UserRepository(UserDataSourse localUserData, UserDataSourse remoteUserData) {
        this.localUserData = localUserData;
        this.remoteUserData = remoteUserData;
    }

    public  static UserRepository  getInstance(UserDataSourse localUserData, UserDataSourse remoteUserData ){
        if (INSTANCE==null){
            INSTANCE=new UserRepository(localUserData,remoteUserData);
        }
        return INSTANCE;
    }

    @Override
    public void saveUser(PersonUserBean user) {
        // TODO: 2018/3/2   远程更新 本地保存
        localUserData.saveUser(user);
    }
    /*
       根据手机号 查询本地是否有已经存在的用户
    */
    @Override
    public void getUserByPhone(String phone,GetUserCallback callback) {
       //本地search
        localUserData.getUserByPhone(phone, new GetUserCallback() {
            @Override
            public void onUserLoaded(PersonUserBean user) {
                callback.onUserLoaded(user);
            }

            @Override
            public void onDataNotAvailable() {
                callback.onDataNotAvailable();
            }
        });
    }

    @Override
    public PersonUserBean getUserSyn(String uid) {
        return localUserData.getUserSyn(uid);
    }

    @Override
    public void getUserAsyn(String uid, GetUserCallback callback) {
        localUserData.getUserAsyn(uid,new GetUserCallback() {
            @Override
            public void onUserLoaded(PersonUserBean user) {
                callback.onUserLoaded(user);
            }

            @Override
            public void onDataNotAvailable() {
                callback.onDataNotAvailable();
            }
        });
    }

    @Override
    public void updateLoginUser(GetUserCallback callback) {
        remoteUserData.updateLoginUser(new GetUserCallback() {
            @Override
            public void onUserLoaded(PersonUserBean user) {
                localUserData.saveUser(user);
                AccountHelper.saveComPany(user);
                if (callback!=null)
                    callback.onUserLoaded(user);
            }

            @Override
            public void onDataNotAvailable() {
                if (callback!=null)
                    callback.onDataNotAvailable();
            }
        });
    }

    public  void  updateLoginUser(){
        updateLoginUser(null);
    }
}
